<template>
  <div class="products-container">
    <!-- 左侧热门排行榜 -->
    <div class="left-panel">
      <div class="rank-container">
        <div class="rank-title">热门农产品排行</div>
        <div class="rank-list">
          <div
            v-for="(item, index) in rankList"
            :key="item.id"
            class="rank-item"
          >
            <div class="rank-number" :class="`rank-${index + 1}`">
              {{ index + 1 }}
            </div>
            <div class="rank-image">
              <el-image :src="item.avatar" fit="cover" :lazy="true">
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="rank-content">
              <div class="product-name">{{ item.name }}</div>
              <div class="product-desc">{{ item.description }}</div>
              <div class="product-info">
                <span class="price">{{ item.price }}</span>
                <span class="sales">销量: {{ item.salesVolume }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧内容区 -->
    <div class="right-panel">
      <!-- 筛选按钮组 -->
      <div class="filter-buttons">
        <div class="button-group">
          <el-button
            :class="{ active: !activeType }"
            @click="handleTypeChange()"
            >全部商品</el-button
          ><el-button
            :class="{ active: activeType === 1 }"
            @click="handleTypeChange(1)"
            >果蔬</el-button
          ><el-button
            :class="{ active: activeType === 2 }"
            @click="handleTypeChange(2)"
            >畜产</el-button
          ><el-button
            :class="{ active: activeType === 3 }"
            @click="handleTypeChange(3)"
            >水产</el-button
          >
        </div>
        <div class="button-group">
          <el-button
            :class="{ active: !isHot && !isPrice }"
            @click="handleSortChange('default')"
            >默认</el-button
          ><el-button
            :class="{ active: isPrice }"
            @click="handleSortChange('price')"
            >价格优先</el-button
          ><el-button
            :class="{ active: isHot }"
            @click="handleSortChange('hot')"
            >销量优先</el-button
          >
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="product-list" v-loading="loading">
        <el-row :gutter="20">
          <el-col v-for="product in products" :key="product.id" :span="6">
            <div class="product-card" @click="handleClick(product.id)">
              <img :src="product.avatar" class="product-image" />
              <div class="product-info">
                <h3>{{ product.name }}</h3>
                <p class="desc">{{ product.description }}</p>
                <div class="bottom">
                  <span class="price">{{ product.price }}</span>
                  <span class="sales">销量: {{ product.salesVolume }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { getHotRank, getProductList } from "@/api/product";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Picture } from "@element-plus/icons-vue";
import request from "@/utils/request";
import type { ApiResponse } from "@/utils/request";

interface Product {
  id: number;
  name: string;
  description: string;
  avatar: string;
  productType: number;
  price: number;
  salesVolume: number;
  productionDate: string;
  expirationDate: string;
  supplierId: number;
  createdBy: string;
  createdTime: string;
  updateBy: string;
  updateTime: string;
  quantity: number | null;
  shoppingCartId: number | null;
  isDeleted: number;
}

// 查询参数
const queryParams = reactive({
  pageNo: 0,
  pageSize: 8,
  productType: undefined as number | undefined,
  isHot: undefined as string | undefined,
  isPrice: undefined as string | undefined,
});

const products = ref<Product[]>([]);
const total = ref(0);
const loading = ref(false);
const router = useRouter();
const searchKey = ref("");
const isSearching = ref(false);
const activeCategory = ref("all");
const sortType = ref("default");
const rankList = ref<Product[]>([]);
const activeType = ref<number>();
const isHot = ref(false);
const isPrice = ref(false);

// 获取商品列表
const fetchProducts = async (): Promise<void> => {
  try {
    const response = await request<Product[]>({
      url: "/agriculturalProduct/queryByProductType",
      method: "post",
      data: {
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
        productType: activeType.value,
        isHot: isHot.value ? "true" : undefined,
        isPrice: isPrice.value ? "true" : undefined,
      },
    });
    if (response?.success) {
      products.value = response.data;
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  }
};

// 获取热门排行榜
const fetchHotRank = async () => {
  try {
    const res = await getHotRank();
    if (res.success) {
      rankList.value = res.data;
    }
  } catch (error) {
    console.error("获取排行榜失败：", error);
    ElMessage.error("获取排行榜失败");
  }
};

// 切换分类
const handleTypeChange = (productType?: number) => {
  activeType.value = productType;
  // 重置排序
  isHot.value = false;
  isPrice.value = false;
  fetchProducts();
};

// 切换排序方式
const handleSortChange = (type: "hot" | "price" | "default") => {
  if (type === "hot") {
    isHot.value = true;
    isPrice.value = false;
  } else if (type === "price") {
    isHot.value = false;
    isPrice.value = true;
  } else {
    isHot.value = false;
    isPrice.value = false;
  }
  fetchProducts();
};

// 页码改变
const handlePageChange = (page: number) => {
  queryParams.pageNo = page - 1; // 因为后端从0开始计数
  fetchProducts();
};

// 点击农产品跳转到详情页
const handleClick = (id: number) => {
  router.push({
    name: "ProductDetail",
    params: { id: id.toString() }, // 确保 id 转为字符串
  });
};

// 搜索产品
const handleSearch = async (): Promise<void> => {
  if (!searchKey.value.trim()) {
    await fetchProducts();
    return;
  }

  try {
    loading.value = true;
    const response = await request<Product[]>({
      url: "/agriculturalProduct/queryByProductType",
      method: "post",
      data: {
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
        productType: activeType.value,
        isHot: isHot.value ? "true" : undefined,
        isPrice: isPrice.value ? "true" : undefined,
      },
    });
    if (response?.success) {
      const filteredProducts = response.data.filter((item) =>
        item.name.toLowerCase().includes(searchKey.value.trim().toLowerCase())
      );
      products.value = filteredProducts;
    }
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败");
  } finally {
    loading.value = false;
  }
};

// 清空搜索
const handleClearSearch = async () => {
  searchKey.value = "";
  isSearching.value = false;
  await fetchProducts();
};

// 获取商品类型文本
const getProductType = (type: number) => {
  const typeMap = {
    1: "果蔬",
    2: "畜产",
    3: "水产",
  };
  return typeMap[type as keyof typeof typeMap] || "其他";
};

// 初始加载
fetchHotRank();
fetchProducts();

onMounted(() => {
  fetchHotRank();
  fetchProducts();
});
</script>

<style lang="scss" scoped>
.products-container {
  display: flex;
  gap: 24px;
  padding: 24px;
  background: #f8fafc;
  min-height: calc(100vh - 60px);
}

.left-panel {
  width: 320px;
  flex-shrink: 0;
}

.rank-container {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  height: auto;
  min-height: 200px;
  position: sticky;
  top: 24px;
}

.rank-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    width: 4px;
    height: 20px;
    background: #409eff;
    margin-right: 8px;
    border-radius: 2px;
  }
}

.rank-list {
  .rank-item {
    display: flex;
    align-items: flex-start;
    padding: 16px 0;
    border-bottom: 1px solid #f5f5f5;
    transition: all 0.3s ease;

    &:hover {
      transform: translateX(4px);
      background: #f8fafc;
      border-radius: 8px;
      padding: 16px 8px;
    }

    &:last-child {
      border-bottom: none;
      padding-bottom: 0;
    }
  }

  .rank-number {
    width: 28px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    border-radius: 8px;
    margin-right: 12px;
    font-weight: 600;
    font-size: 15px;
    flex-shrink: 0;

    &.rank-1 {
      background: linear-gradient(135deg, #ff6b6b, #ff4757);
      color: white;
    }

    &.rank-2 {
      background: linear-gradient(135deg, #ff9f43, #ff7f50);
      color: white;
    }

    &.rank-3 {
      background: linear-gradient(135deg, #ffd93d, #ffb142);
      color: white;
    }
  }

  .rank-image {
    width: 80px;
    height: 80px;
    margin-right: 12px;
    flex-shrink: 0;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .el-image {
      width: 100%;
      height: 100%;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.05);
      }
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      color: #909399;
    }
  }

  .rank-content {
    flex: 1;
    min-width: 0;

    .product-name {
      font-size: 16px;
      color: #1a1a1a;
      margin-bottom: 6px;
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .product-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      line-height: 1.4;
    }

    .product-info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .price {
        color: #ff4d4f;
        font-size: 18px;
        font-weight: 600;
      }

      .sales {
        color: #999;
        font-size: 13px;
        background: #f5f7fa;
        padding: 2px 8px;
        border-radius: 12px;
      }
    }
  }
}

.right-panel {
  flex: 1;
}

.filter-buttons {
  background: #fff;
  padding: 16px 24px;
  border-radius: 16px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);

  .button-group {
    display: inline-flex;
    gap: 8px;

    .el-button {
      margin: 0;
      border-radius: 8px;
      padding: 10px 20px;
      font-size: 14px;
      font-weight: 500;
      transition: all 0.3s ease;

      &.active {
        background: #409eff;
        color: #fff;
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        transform: translateY(-1px);
      }

      &:hover:not(.active) {
        color: #409eff;
        border-color: #409eff;
        background: #ecf5ff;
      }
    }
  }
}

.product-list {
  .el-row {
    margin: -12px;

    .el-col {
      padding: 12px;
    }
  }

  .product-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 0;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);

    &:hover {
      transform: translateY(-6px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);

      .product-image {
        transform: scale(1.05);
      }
    }

    .product-image {
      width: 100%;
      height: 220px;
      object-fit: cover;
      transition: transform 0.3s ease;
    }

    .product-info {
      padding: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        color: #1a1a1a;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .desc {
        margin: 8px 0 12px;
        color: #666;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        line-height: 1.4;
        height: 40px;
      }

      .bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12px;

        .price {
          color: #ff4d4f;
          font-size: 20px;
          font-weight: 600;
          position: relative;
          padding-left: 14px;

          &::before {
            content: "¥";
            font-size: 14px;
            position: absolute;
            left: 0;
          }
        }

        .sales {
          color: #999;
          font-size: 13px;
          background: #f5f7fa;
          padding: 4px 12px;
          border-radius: 12px;
        }
      }
    }
  }
}

// 覆盖 element-plus 的默认样式
:deep(.el-button + .el-button) {
  margin-left: 0;
}
</style> 